//引入模块
const express = require("express");
//引入mysql连接池对象
const query = require("../util/query.js");
const { handleImgUrl } = require("../util/common.js");

//创建空路由器
let router = express.Router();
//挂载路由
// 1.8. 图片分享
//===============================================
// 1.8.1 查询图片分享分类 photo/getimgcategory
// 参数名	参数说明	备注
// 无参数
router.get("/category", async (req, res) => {
  try {
    //1获取数据
    //2验证数据
    //3执行SQL语句
    let sql =
      "select id,title from photo_category where `status` = 1 ORDER BY sort ";

    let result = await query(sql);
    let data = result;
    data.unshift({id: 0 , title: '全部' })   //添加一个记录在数组的开始位置
    res.send({ code: 1, msg: `获取成功`, data }); //throw err;
  } catch (error) {
    res.send({ code: -1, msg: `获取失败, error: ${error}` }); //throw err;
  }
});

//======================================================================
// 1.8.2 根据分类id查询图片列表 photo/getimages
// 参数名	参数说明	备注
// id	图片分享分类id，如果id参数为0则表示查询所有分类的图片列表
router.get("/list", async (req, res) => {
  try {
    //接收参数
    let category_id = req.query.category_id;
    category_id = parseInt(category_id) || 0;

    //建sql语句
    let sql = `select id,title,img,summary from photo `;
    if (category_id ) {
      sql += `where category_id = ${category_id}`;
    
    }    

    //执行Query
    let result = await query(sql);
    let data = result;    
    res.send({ code: 1, msg: `获取成功`, data }); //throw err;
  } catch (error) {
    res.send({ code: -1, msg: `获取失败, error: ${error}` }); //throw err;
  }
});

//======================================================================
// 1.8.3 根据图片资讯id查询图片资讯详情 photo/getimages
// 参数名	参数说明	备注
// id	图片资讯id
router.get("/detail", async (req, res) => {
  try {
    //接收参数
    let id = req.query.id;
    id = parseInt(id);

    //建sql语句
    let sql = `select id,title,count,content from photo where id = ${id}`;

    //执行Query
    let result = await query(sql);
    let data = result;

    res.send({ code: 1, msg: `获取成功`, data }); //throw err;
  } catch (error) {
    res.send({ code: -1, msg: `获取失败, error: ${error}` }); //throw err;
  }
});

//======================================================================
// 1.8.4 根据图片资讯id查询图片资讯中的图片列表 photo/getthumimages
// 参数名	参数说明	备注
// id	图片资讯id
router.get("/detail_list", async (req, res) => {
  try {
    //接收参数
    let id = req.query.id;
    id = parseInt(id) || 0;

    //建sql语句
    let sql = `select img  from photo_details where photo_id = ${id}`;

    //执行Query
    let result = await query(sql);
    let data = result;
    
    res.send({ code: 1, msg: `获取成功`, data }); //throw err;
  } catch (error) {
    res.send({ code: -1, msg: `获取失败, error: ${error}` }); //throw err;
  }  
});
//===============================================
//导出路由器
module.exports = router;
